/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief Implementation for Dummy interface client library.
 * \author Antti Maula <antti.maula@tkk.fi>
 *
 * $Id: DummyClient.cpp,v 1.15 2009-12-08 10:48:27 morsko Exp $
 *
 */

#include "DummyClient.hpp"
#include "DummyData.hpp"

//*****************************************************************************
using namespace MaCI::Dummy;
//*****************************************************************************
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CDummyClient::CDummyClient(gimi::GIMI *aGIMIPtr, 
                           const int aInterfaceMinor)
  : CSync(1,1), // Max One Mutex, Max one Condition
    CThread(1), // Max one Thread.
    CMaCI(aGIMIPtr, GIMI_PROTOCOL_MACI_DUMMY, aInterfaceMinor),
    iDummyDataSequence(0),
    iLastDummyData(),
    iDummyClientCallback(NULL)
{
  dPrint(4,"CDummyClient %p constructed", this);
}
//*****************************************************************************

CDummyClient::~CDummyClient()
{
  DoClose();
  dPrint(4,"CDummyClient %p destructed", this);
}
//*****************************************************************************

MaCI::EMaCIError CDummyClient::DoOpen(void)
{

  EMaCIError result = KMaCIError;
  
  // Checks.
  if(!IsActive()) {

    // Do Subs. using the MaCI provided function.
    result = SubscribeToInterface();

    // If all inits were fine...
    if (result == KMaCIOK) {
      // Start the Thread
      SetActive(true);
      EnableSynchronousMessageReply();
      CThread::RunThread();
      dPrint(4,"CDummyClient::DoOpen() was succesfull.");
    }

  } else {
    dPrint(4,"DummyClient already Active, not Opening again.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CDummyClient::DoClose(void)
{
  EMaCIError result = KMaCIError;

  if(IsActive()) {
    SetActive(false);

    // Wait for thread to complete.
    CThread::SetRequestTermination();
    /* CThread::CancelThread(); //Removed by script */
    CThread::WaitThread();

    result = UnsubscribeToInterface(TimeoutValue(2000));
  
    if(result == KMaCIOK){
      dPrint(4,"Succesfully closed DummyClient");    
    }else{
      dPrint(4,"Unsubscribing failed!");
    }
  
    
  } else {
    dPrint(4, "DummyClient not active, so not Closing.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

bool CDummyClient::GetDummyEvent(CDummyData &aData,
                                 unsigned int *aSeq,
                                 const unsigned int aTimeout_ms)
{  
  bool result = false;
  
  // Fallback in case the class is not active.
  if (!IsActive()) return false;

  Lock();
  
  if (aSeq == NULL) {
    // No sequence number defined. Just do direct copy of local data - no sync
    aData = iLastDummyData;
    result = true;
    
  } else {
    
    if (iDummyDataSequence <= *aSeq) {
      int time_left = aTimeout_ms;
      unsigned int time_begin = ownTime_get_ms();

      // The available scan is older than requested - must wait for time_left
      do {
        Wait(time_left, KEventDummyData);
	time_left = aTimeout_ms - ownTime_get_ms_since(time_begin);
	
      } while(IsActive() && iDummyDataSequence < *aSeq && time_left > 0);
      
      // Now, check whether the waiting resulted in the correct sequence
      if (iDummyDataSequence > *aSeq) {
	// Yes :)
	aData = iLastDummyData;
	*aSeq = iDummyDataSequence;
	result = true;
        //dPrint(1,"Got data. *aSeq = %d, iDummyDataSequence = %d", *aSeq, iDummyDataSequence);
	
      } else {
	// No :(
	dPrint(3, "Failed to get DummyData! (Timeout %dms)",
	       aTimeout_ms);
      }
      
    } else {
      // The available data is newer or matching.
      aData = iLastDummyData;
      *aSeq = iDummyDataSequence;
      //      dPrint(1,"Got data. *aSeq = %d, iDummyDataSequence = %d", *aSeq, iDummyDataSequence);
      result = true;
    }
  }
  
  Unlock();
  
  return result;
}
//*****************************************************************************

bool CDummyClient::GetRandomNumberBySynchronousCall(unsigned int &aNumber, 
                                                    unsigned int aTimeout_ms)
{
  // REMEMBER: THIS IS JUST AN EXAMPLE OF AN SYNCHRONOUS CALL ON
  // CLIENT SIDE!

  bool result = false;
  CDummyData rd;
  CDummyData dd;
  dd.CreateInternalBinBag();

  // Get a sequence.
  const unsigned int mySequence = GetUniqueMessageID();
      
  // Set timestamp to current (default constructor of Common::TTimestamp)
  dd.SetTimestamp(Common::TTimestamp());
  
  // Add a dummy event
  dd.SetCommand(TCommand(KCommandGetRandomNumber));
  
  // Send! ( Should probably check the Send() - but timeouted receive
  // gives the same )
  SendCommand(dd, mySequence);

  // Now, get reply!
  GetCommandReply(rd, mySequence, aTimeout_ms);

  // Extract data.
  const TDummyEvent *de = rd.GetDummyEvent();
  if (de) {
    aNumber = de->data;
    result = true;
  }

  return result;
}
//*****************************************************************************

bool CDummyClient::
GetRandomNumberBySynchronousCall(std::vector<unsigned int> &aNumberArray, 
                                 unsigned int aCount, unsigned int aTimeout_ms)
{  
  // REMEMBER: THIS IS JUST AN EXAMPLE OF AN MULTIPLE-MESSAGE
  // SYNCHRONOUS CALL ON CLIENT SIDE!

  bool result = false;
  std::vector<CDummyData> replyDataArray;      // for Data replies
  std::vector<SMessageSource> replySourceArray; // for sources.
  std::vector<int> messageIDArray; // for messageids.
  CDummyData dd; // For command.
  dd.CreateInternalBinBag();

  // Clear output array
  aNumberArray.clear();

  // Generate messageIDs.
  for(unsigned int i = 0; i < aCount; ++i) {
    messageIDArray.push_back(GetUniqueMessageID());
  }
  
  // Set timestamp to current (default constructor of Common::TTimestamp)
  // Don't care even all sent messages have the same timestamp :)
  dd.SetTimestamp(Common::TTimestamp());
  
  // Add a dummy event
  dd.SetCommand(TCommand(KCommandGetRandomNumber));
  
  // Now send multiple commands in sequence.
  for(EACH_IN_i(messageIDArray)) {
    SendCommand(dd, *i);
  }

  // Now, get replies for ALL! (In this example, we require ALL or NOTHING)
  if (ReceiveSynchronousMessageReply(replyDataArray, replySourceArray, messageIDArray, aTimeout_ms) == KMaCIOK) {
    for(EACH_IN_i(replyDataArray)) {
      // Extract data.
      const TDummyEvent *de = i->GetDummyEvent();
      if (de) {
        aNumberArray.push_back(de->data);

      } else {
        dPrint(1,"WARNING: Got element with NO event data! "
               "Still reporting all OK, but less numbers have been generated!");
        
      }
    }
    // Operation was succesfull, as we got all entries
    result = true;
  }


  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
#if 0
/**
 * This function is an _EXAMPLE_ of a directly receiving
 * function. When this function model is used, the Client class
 * doesn't have to implement a separate thread. (ProcessMessage and
 * ThreadFunction are not used). However, this means that no special
 * processing can be done by the interface hence this model is only
 * suitable for simple interfaces. This can ofcourse be later changed
 * without changing the public interface, so it's not a
 * architecturally significant decision. Use of this model is also
 * encouraged if possible, as it saves one extra thread thus saving a
 * (minimal) fraction of system resources.
 *
 * As this DummyClient uses the more complex processing model as
 * example, this code block is disabled with precompiler directive,
 * but left here as on fully working example of receiving MaCI
 * dataelements directly from GIMI.
 *
 * @param[out] aData        Data will be stored in this container
 * @param[in] aTimeout_ms   Timeout time for this call.
 */
bool CDummyClient::GetDummyEvent(CDummyData &aData,
                                 const unsigned int aTimeout_ms);
{
  EMaCIError result;
  gimi::GIMIMessage gmsg;
  
  if (IsActive()) {
    
    // Call the ReceiveMessage wrapper with 2s timeout
    result = ReceiveInterfaceMessage(gmsg, aTimeout_ms);
    
    // If result is OK, process the msg.
    if (result == KMaCIOK) {
      bool r;
      gim::binbag::CBinBag bb;
      CDummyData d;
      
      // Decode BinBag.
      r = bb.Decode(gmsg.getData(), gmsg.getDatalength());
      if (r) {
        // BinBag OK. Decode DummyData.
        r = d.DecodeFrom(&bb);
        if (r && d.GetDummyEvent()) {
          // DummyData ok. Copy to caller.
          aData.Copy(d);
          
        } else {
          result = KMaCIInvalidFormat;
          
        }
        
      } else {
        result = KMaCIInvalidFormat;
        
      }
    }
  } else {
    result = KMaCINotActive;

  }
  
  return (result == KMaCIOK);
}
#endif
//*****************************************************************************

bool CDummyClient::GetCommandReply(CDummyData &aDummyData, const int aMessageID, 
                                   const int aTimeout_ms)
{ 
  EMaCIError result;
  SMessageSource ms; // Compulsory for call to
                     // Receivesynchronousmessagereply, not used here
                     // though.

  // Call the ReceiveMessage wrapper with 2s timeout
  result = ReceiveSynchronousMessageReply(aDummyData, ms, aMessageID, aTimeout_ms);
  
  // If result is OK, process the msg.
  if (result == KMaCIOK) {
    // Got message OK.  Basicly we don't need to do anything here, but
    // some interface may want to do some checks: for example, the
    // received message contains some specific element or information
    // before it is accepted.
  }
  
  return (result == KMaCIOK);
}
//*****************************************************************************

bool CDummyClient::SendCommand(const CDummyData &aDummyData, const int aMessageID)
{
  EMaCIError result = KMaCIError;
  
  if (IsActive()) {
    if (aDummyData.GetCommand()) {
      // Send.
      SendInterfaceMessage(aDummyData.GetBinBagContainerPtr()->GetBuffer(),
                           aDummyData.GetBinBagContainerPtr()->GetBufferSize(),
                           aMessageID);
      
      dPrint(10,"SendInterfaceMessage called: %d:%d (%d bytes of payload sent)",
             iInterfaceMajor, iInterfaceMinor, 
             aDummyData.GetBinBagContainerPtr()->GetBufferSize());
      // Result
      result = KMaCIOK;
      
    } else {
      dPrint(2,"No 'TCommand' element in provided CDummyData object. Will not send!");
      result = KMaCIInvalidFormat;

    }
   
  } else {
    dPrint(2,"Unable to send DummyData - Interface is not active! (Open() not called?)");
    result = KMaCINotActive;

  }


  return (result == KMaCIOK);
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

int CDummyClient::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CDummyData id;
  bool r;

  r = bb.Decode(msg.getData(), msg.getDatalength());
  if (r) {
    // Succesfully decoded as BinBag.
    r = id.DecodeFrom(&bb);
    if (r) {
      // Succesfully decoded as Dummy, now handle contents
      Lock();
      if (id.GetDummyEvent()) {
        iLastDummyData = id;
        ++iDummyDataSequence;
        Notify(KEventDummyData);
        dPrint(10,"Got DummyData, Sequence now %u", iDummyDataSequence);
      }
      Unlock();
      
      // Call the handler if set.
      if (iDummyClientCallback) {
        dPrint(8,"Got Callback for DummyDataEvent - executing!");
        iDummyClientCallback->OnDummyDataEvent(id,
                                               iDummyDataSequence,
                                               *this);
        dPrint(8,"Callback for DummyDataEvent - execution complete!");
      } 

    } else {
      dPrint(4,"WARNING: Received Dummy interface message, but failed to decode as DummyData!");
      
    }
  }
  
  return result;
}

//*****************************************************************************

int CDummyClient::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  const unsigned int hard_error_count_limit = 10;
  unsigned int hard_error_count = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(8, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(IsActive()) {
    // Call the ReceiveMessage wrapper with 1s timeout
    e = ReceiveInterfaceMessage(gmsg, 1000);
    if (e == KMaCIOK) {
      ProcessMessage(gmsg);

      // Reset error counter.
      if (hard_error_count) hard_error_count = 0;

    } else if (e != KMaCITimeout) {
      // Increment hard error count
      ++hard_error_count;
      
      // Check whether the hard error count limit is still under limit. 
      if (hard_error_count < hard_error_count_limit) {
        // Other error, try to recover by sleeping one second.
        dPrint(10,"ProcessMessage returned error %u, trying to recover by sleeping 1000ms (%u attempts left)",
               e, hard_error_count_limit-hard_error_count);
        ownSleep_ms(1000);

      } else {
        dPrint(3,"Error Recovery failed, DummyClient ThreadFunction terminating...");

        // Break the while().
        break;
      }
      
    }
  }
  
  dPrint(8, "GIMIMessage handler stopped");
  SetActive(false);

  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
